package Cluedo.GUI2;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;

import Cluedo.API.CDialog;
import Cluedo.API.CardImage;
import Cluedo.API.DisproofAlert;
import Cluedo.API.LanguagePack;
import Cluedo.API.SuggestionAlert;
import Cluedo.Controller.GameController;

/**
 * Displays suggestions made and allows the user to see the card used for the disproof.
 * 
 * @author Alex
 */
public class SuggestionNotification extends CDialog implements ActionListener {

	CardImage disprovePlayer = null;
	CardImage[] candidateCards = new CardImage[3];
	JButton doneButton = null;
	JButton showButton = null;
	
	String [] names = new String[3];
	String playerName = "";
	
	GameController gameController = null;

	boolean disposed = false;

	int timeOut = 4000;
	
	DisproofAlert disproofAlert = null;
	
	private static String DEFAULT_GROUP = "suggest_notification";
	
	public void actionPerformed(ActionEvent e) {
		if(e.getActionCommand().equals("done_button")) {
			setVisible(false);
			dispose();

		}
		if(e.getActionCommand().equals("view_card_button")) {
			JOptionPane.showMessageDialog(null, "Card is : " + disproofAlert.getCardShown());

		}

	}

	public SuggestionNotification (JFrame parent, DisproofAlert disproofAlert, GameController gameController) {
		super("Suggestion notification..", true);
		setParent((Frame)parent);
		this.gameController = gameController;
		
		this.disproofAlert = disproofAlert;
		
		SuggestionAlert originalSuggestionAlert = disproofAlert.getOriginalSuggestion();
		playerName = originalSuggestionAlert.getSuggestedBy();

		for(int i = 0; i < 3; i++) {
			String cardName = "";
			switch(i) {
				case 0 :
					cardName = originalSuggestionAlert.getWho().getName();
				break;
				case 1 :
					cardName = originalSuggestionAlert.getWhat().getName();
				break;
				case 2 :
					cardName = originalSuggestionAlert.getWhere().getName();
				break;
			}
			if(cardName != null)
				names[i] = (cardName);
			else {
				System.out.println("[SuggestionNotification:] unrecoverable error in message");
			}
		}

		doneButton = new JButton(LanguagePack.getString("done_button", DEFAULT_GROUP));
		showButton = new JButton(LanguagePack.getString("view_card_button", DEFAULT_GROUP));
		
		doneButton.addActionListener( this );
		doneButton.setActionCommand("done_button");

		showButton.addActionListener( this );
		showButton.setActionCommand("view_card_button");
		
		
		String playerCharacter = gameController.getBoard().getPlayer(playerName).getCharacter();
		disprovePlayer = new CardImage("Resources/Cards/" + playerCharacter.toLowerCase() + ".gif", playerName);

		disprovePlayer.setBorder( BorderFactory.createEtchedBorder() );


		for(int i = 0; i < names.length; i++) {
			if(new java.io.File("Resources/Cards/" + names[i].toLowerCase() + ".gif").exists() == true)
				candidateCards[i] = new CardImage("Resources/Cards/" + names[i].toLowerCase() + ".gif", names[i]);
			else
				candidateCards[i] = new CardImage(names[i].toLowerCase(), names[i]);
		}



		String disproofMessage = "";
		
		if(!disproofAlert.getDisprovedBy().equals(""))
			disproofMessage = addArguments(LanguagePack.getString("suggest_disproved", DEFAULT_GROUP), new String[] { disproofAlert.getDisprovedBy() });
		else
			disproofMessage = LanguagePack.getString("suggest_not_disproved", DEFAULT_GROUP);
		System.out.println(disproofMessage);
			
		
		JPanel topPage = new JPanel();
		topPage.setLayout( new BorderLayout() );
		
		Box headerPage = Box.createVerticalBox();

		Box cardViewPage = Box.createHorizontalBox();
		Box bottomPage = Box.createVerticalBox();
		
		Box disprovePlayerColumn = Box.createVerticalBox();
		Box candidateCardsColumn = Box.createHorizontalBox();
		
		JPanel cardRowPanel = new JPanel();
		GridLayout newGridLayout = new GridLayout();
		newGridLayout.setHgap(10);
		cardRowPanel.setLayout( newGridLayout );

		
		disprovePlayerColumn.add( disprovePlayer );

		for(int i = 0; i < names.length; i++) {
			cardRowPanel.add( candidateCards[i] );
			candidateCards[i].setBorder( BorderFactory.createEtchedBorder() );

		}		
		
		candidateCardsColumn.add( cardRowPanel );
		JLabel titleLabel = new JLabel(
				addArguments(LanguagePack.getString("suggest_made_by", DEFAULT_GROUP), new String[] { playerName }));
				
		titleLabel.setFont( new Font( "Arial", Font.BOLD, 17) );
		headerPage.add( titleLabel );
		headerPage.add( Box.createVerticalStrut(20) );


		headerPage.add( new JSeparator(SwingConstants.HORIZONTAL) );
		headerPage.add( Box.createVerticalStrut(20) );
						
		cardViewPage.add( disprovePlayerColumn );
		cardViewPage.add( Box.createHorizontalStrut(60) );
		cardViewPage.add( candidateCardsColumn );


		bottomPage.add( Box.createVerticalStrut(20) );	
		
		JLabel disproofMessageLabel = new JLabel( disproofMessage );
		disproofMessageLabel.setFont( new Font( "Arial", Font.PLAIN, 17) );
			
		bottomPage.add( disproofMessageLabel );
		bottomPage.add( Box.createVerticalStrut(30) );
		bottomPage.add( doneButton );

		/** Only show the view disproof card to suggestions made by humans */
		if(gameController.getBoard().getPlayer(originalSuggestionAlert.suggestedBy).getPlayerType() == 0
				&& disproofAlert != null && !disproofAlert.cardShown.equals("")) {
			bottomPage.add( Box.createHorizontalStrut(30) );
			bottomPage.add( showButton );
		}

	
		topPage.add(headerPage, BorderLayout.NORTH);
		
		topPage.add(cardViewPage, BorderLayout.CENTER);

		JLabel playerNameLabel = new JLabel( playerName );       
		playerNameLabel.setFont( new Font( "Arial", Font.BOLD, 17) );

		topPage.add( playerNameLabel , BorderLayout.SOUTH);
		
		getContentPane().add(topPage, BorderLayout.NORTH);
		getContentPane().add(bottomPage, BorderLayout.SOUTH);
		pack();
		centre();
		setResizable(false);
	
//		Thread closer = new Thread() {
//			public void run() {
//				decay();	
//			}
//		};
//		closer.start();
		//setVisible(true);

	}
	public void centre() {
    		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    		Dimension frameSize = getSize();
    		frameSize.height = ((frameSize.height > screenSize.height) ? screenSize.height : frameSize.height);
    		frameSize.width = ((frameSize.width > screenSize.width) ? screenSize.width : frameSize.width);
    		setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
	}


	public void selectedEvent() {
		for(int i = 0; i < candidateCards.length; i++)
			candidateCards[i].setEnabled(false);
	}

	synchronized public void decay() {
		if(isVisible() == true) {
			System.out.println("[SuggestionNotification:decay] Called");		
			try {
				Thread.sleep(timeOut);
			}
			catch(Exception e ) {
				System.out.println("Can't get no sleep");
			}
                	
			System.out.println("[SuggestionNotification:decay] Done");
			setVisible(false);
			dispose();
		}
	}
		
	
	/**
	 * Adds relevant arguments to string from String array 
	 * 
	 * @param string
	 * @param names2
	 * @return formatted string
	 */
	private static String addArguments(String string, String[] names2) {
		for(int i=0;i<names2.length;i++)
			string = string.replaceAll("%"+(i+1), names2[i]);
		if(string.indexOf("@@") > -1) {
			string = addBreaks(string);
		}
		return string;
	}
	
	
	/**
	 * @param string
	 * @return
	 */
	private static String addBreaks(String string) {
		string = string.replaceAll("@@", "<br>");
		string = Cluedo.API.Constants.HTML_ON + string + Cluedo.API.Constants.HTML_OFF;
		return string;
	}
}
